package account

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"strings"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetAccountPageApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAccountPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAccountPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetAccountPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetAccountPageApiLogic) GetAccountPageApi(req *types.GetAccountPageReq) (resp *types.AccountPageResp, err error) {
	accountType := cast.ToInt64(l.ctx.Value("accountType")) // 账号类型,0表示超管,1表示后台运营人员,2表示企业账号,3表示门店账号
	accountId := cast.ToInt64(l.ctx.Value("accountId"))     // 当前登录用户id
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	offset, limit := utils.DbPage(req.PageNumber, req.PageSize)
	tx := dao.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.EnterpriseID.Eq(enterpriseId))
	if req.Username != "" {
		req.Username = strings.ReplaceAll(req.Username, "%", "\\%")
		req.Username = strings.ReplaceAll(req.Username, "_", "\\%")
		tx = tx.Where(dao.EnterprisePersonEntity.Name.Like("%" + req.Username + "%"))
	}
	if req.Status != "" {
		tx = tx.Where(dao.AccountEntity.Status.Eq(cast.ToInt64(req.Status)))
	}

	// 账号类型搜索
	if req.AccountType != "" {
		tx = tx.Where(dao.AccountEntity.AccountType.Eq(cast.ToInt64(req.AccountType))) // 账号类型,0表示超管,1表示后台运营人员,2表示企业账号,3表示门店账号
	}
	// 如果是企业账号或门店的时候需要加上条件,只查询当前账号下的数据
	if k.IsContains([]int64{2, 3}, accountType) {
		fmt.Println(accountId)
		//tx = tx.Where(dao.AccountEntity.ParentID.Eq(accountId))
	}
	tx = tx.Select(dao.AccountEntity.ALL, dao.EnterprisePersonEntity.Name.As("PersonName")).LeftJoin(dao.EnterprisePersonEntity, dao.EnterprisePersonEntity.ID.EqCol(dao.AccountEntity.PersonID))

	var accountEntities = make([]*bo.AccountEntityBo, 0)
	count, err := tx.Order(dao.AccountEntity.AccountID.Desc()).ScanByPage(&accountEntities, offset, limit)
	if err != nil {
		return &types.AccountPageResp{
			Data: make([]types.AccountModel, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      count,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	// 企业账号列表
	enterpriseIdList := k.Distinct(k.Map(k.Filter(accountEntities, func(item *bo.AccountEntityBo, index int) bool {
		return item.AccountType == 2
	}), func(item *bo.AccountEntityBo, index int) int64 {
		return item.EnterpriseID // 企业enterprise表id
	}))
	// 找到企业名字
	enterpriseEntities, _ := dao.EnterpriseEntity.WithContext(l.ctx).Where(dao.EnterpriseEntity.ID.In(enterpriseIdList...)).Find()
	enterpriseNameMap := k.ToMap(enterpriseEntities, func(item *model.EnterpriseEntity) (int64, string) {
		return item.ID, item.Name
	})
	// 门店账号列表
	customerIdList := k.Distinct(k.Map(k.Filter(accountEntities, func(item *bo.AccountEntityBo, index int) bool {
		return item.AccountType == 3
	}), func(item *bo.AccountEntityBo, index int) int64 {
		return item.CustomerID
	}))
	customerEntities, _ := dao.EnterpriseCustomerEntity.WithContext(l.ctx).Where(dao.EnterpriseCustomerEntity.ID.In(customerIdList...)).Find()
	// 门店名字
	customerMap := k.ToMap(customerEntities, func(item *model.EnterpriseCustomerEntity) (int64, string) {
		return item.ID, item.Name
	})
	// 客户id和企业id的map映射
	accountData := k.Map(accountEntities, func(item *bo.AccountEntityBo, index int) types.AccountModel {
		address := &utils.CityInfo{}
		if item.LastLoginIP != "" {
			address = utils.GetIpToAddress(item.LastLoginIP)
		}
		var enterpriseName = "平台用户"
		var customerName = ""
		if item.AccountType == 2 { // 企业的时候
			enterpriseName = enterpriseNameMap[item.EnterpriseID]
		} else if item.AccountType == 3 { // 门店账号
			customerName = customerMap[item.CustomerID]
		}
		return types.AccountModel{
			AccountID:      item.AccountID,                                                                    // 主键id
			Username:       item.Username,                                                                     // 用户名
			AccountType:    item.AccountType,                                                                  // 账号类型,0表示超管,1表示后台运营人员,2表示企业账号,3表示门店账号
			EnterpriseId:   item.EnterpriseID,                                                                 // 企业id
			EnterpriseName: enterpriseName,                                                                    // 企业名称
			CustomerId:     item.CustomerID,                                                                   // 客户id
			CustomerName:   customerName,                                                                      // 客户名称
			PersonName:     item.PersonName,                                                                   // 员工名称
			Status:         item.Status,                                                                       // 状态0表示正常,1表示禁用
			LastLoginDate:  k.If(item.LastLoginDate.IsZero(), 0, utils.TimestampToString(item.LastLoginDate)), // 最后登录时间
			LastLoginIP:    item.LastLoginIP,                                                                  // 最后登录ip地址
			Country:        k.If(address != nil, address.Country, ""),                                         // 国家
			Province:       k.If(address != nil, address.Province, ""),                                        // 省份
			City:           k.If(address != nil, address.City, ""),                                            // 城市
			CreatedAt:      utils.TimestampToString(item.CreatedAt),                                           // 创建时间
			UpdatedAt:      utils.TimestampToString(item.UpdatedAt),                                           // 更新时间
		}
	})
	return &types.AccountPageResp{
		Data: accountData,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
